package com.example.yang.samapp;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;

/**
 * Created by Yang on 2016/9/19.
 */
public class Basketball_btn extends Button{
private String countdownStr,resentStr;
    private Drawable beforeSendBgDrawable,afterSendDrawable;
    private int beforeSendTextColor,afterSendTextColor;

    public Basketball_btn(Context context) {
        this(context,null);
    }

    public Basketball_btn(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public Basketball_btn(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ma=context.obtainStyledAttributes(attrs,R.styleable.Basketball_btn);
        final int startNum=ma.getInt(R.styleable.Basketball_btn_startNum,60);
        final String sendVerifyCodeStr=ma.getString(R.styleable.Basketball_btn_sendVerifyCodeStr);
        countdownStr=ma.getString(R.styleable.Basketball_btn_countdownStr);
        resentStr=ma.getString(R.styleable.Basketball_btn_resentStr);
        if (countdownStr==null) countdownStr="已发送";
        if (resentStr==null) resentStr="重新发送";
        beforeSendBgDrawable=ma.getDrawable(R.styleable.Basketball_btn_beforeSendBgDrawable);
        afterSendDrawable=ma.getDrawable(R.styleable.Basketball_btn_afterSendBgDrawable);
        beforeSendTextColor=ma.getColor(R.styleable.Basketball_btn_beforeSendTextColor,beforeSendTextColor);
        afterSendTextColor=ma.getColor(R.styleable.Basketball_btn_afterSendTextColor,afterSendTextColor);
        ma.recycle();
        if (sendVerifyCodeStr==null) setText(sendVerifyCodeStr);
        if (beforeSendBgDrawable==null) setBackgroundDrawable(beforeSendBgDrawable);
        setTextColor(beforeSendTextColor);


        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               new CountdownThread(startNum).start();
                setEnabled(false);
                if (afterSendDrawable==null) setBackgroundDrawable(afterSendDrawable);
                setTextColor(afterSendTextColor);
            }
        });
    }
    class CountdownThread extends CountDownTimer{
        private int seconds;
        public CountdownThread(int secondsInfuture){
            super(secondsInfuture*1000,1000);
            this.seconds=secondsInfuture;
        }
        @Override
        public void onTick(long millisUntilFinished) {

            seconds--;
            setText(countdownStr+seconds+"s");
        }
        @Override
        public void onFinish() {
            setText(resentStr);
            setEnabled(true);
            if (beforeSendBgDrawable!=null) setBackgroundDrawable(beforeSendBgDrawable);
            setTextColor(beforeSendTextColor);
        }
    }



}
